import requests
import base64

import tempfile

# 获取系统临时目录路径（自动适应不同操作系统）

#提供一个图片判断其log所归属谁
class ImageAI:
    def __init__(self):
        self.client_id = 'FuuciN8YOl6R6VmoVsmUtc0b'
        self.client_secret = 'BxDfmkSR4EAeG6yzv3m5RsrfResPdexs'
        self.access_token = self._get_access_token()
        self.headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }

    def _get_access_token(self):
        """获取百度AI平台的access_token"""
        auth_url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={self.client_id}&client_secret={self.client_secret}"

        try:
            response = requests.post(auth_url)
            if response.status_code == 200:
                return response.json().get('access_token')
            else:
                raise Exception(f"获取token失败: {response.text}")
        except Exception as e:
            raise Exception(f"认证请求异常: {str(e)}")

    def recognize_logo(self, image_path=None, image_url=None):
        """
        Logo识别接口
        :param image_path: 本地图片路径
        :param image_url: 网络图片URL
        :return: 识别结果
        """
        if not image_path and not image_url:
            raise ValueError("必须提供image_path或image_url参数")

        url = f"https://aip.baidubce.com/rest/2.0/image-classify/v2/logo?access_token={self.access_token}"
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }

        # 处理图片数据
        if image_path:
            with open(image_path, 'rb') as f:
                image_data = base64.b64encode(f.read()).decode('utf-8')
            payload = {'image': image_data}
        else:
            payload = {'url': image_url}

        try:
            response = requests.post(url, headers=headers, data=payload)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            raise Exception(f"Logo识别请求失败: {str(e)}")

image_ai= ImageAI()


